package com.feihong.txgw.observer;

import android.app.Activity;
import android.content.ContentResolver;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Handler;
import android.provider.Telephony;
import android.text.TextUtils;

import com.blankj.utilcode.util.LogUtils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author wangziheng
 * @name txgw_app
 * @class name：com.feihong.txgw.observer
 * @class describe:  短信监听类  {@link android.content.ContentProvider}负责提供共享数据
 * {@link ContentResolver} 负责解析共享数据 {@link ContentObserver} 负责监听共享数据的变化  当有新短信时  触发{@link #onChange(boolean)}然后用ContentResolver去解析
 * @time 2017/10/25 17:09
 * @change
 * @chang time
 * @class describe
 */
public class SmsObserver extends ContentObserver {
    private static final String SMS_URI_INBOX = "content://sms/inbox";
    private static final String SMS_URI = "content://sms";
    private static final String[] PROJECTION = new String[]{
            Telephony.Sms._ID,
            Telephony.Sms.ADDRESS,
            Telephony.Sms.BODY,
            Telephony.Sms.DATE
    };
    private Activity mActivity = null;
    private String smsContent = "";
    private SmsListener mSmsListener;
    private String mAddressTail;
    private String mSmsBodyContains;

    /**
     * Creates a content observer.
     *
     * @param handler The handler to run {@link #onChange} on, or null if none.
     */
    public SmsObserver(Handler handler, Activity activity, SmsListener smsListener, String address, String bodyContains) {
        super(handler);
        mActivity = activity;
        mSmsListener = smsListener;
        mAddressTail = address;
        mSmsBodyContains = bodyContains;
    }

    @Override
    public void onChange(boolean selfChange) {
        super.onChange(selfChange);
        Cursor cursor = null;
        ContentResolver contentObserver = mActivity.getContentResolver();
//        cursor = contentObserver.query(Uri.parse(SMS_URI_INBOX), new String[]{
//                "_id", "address", "body", "read"}, "body like ? and read = ? ", new String[]{"&通讯100&", "0"}, "date desc");

        cursor = contentObserver.query(Uri.parse(SMS_URI_INBOX), PROJECTION, Telephony.Sms.READ + "=?", new String[]{"0"}, Telephony.Sms.Inbox.DEFAULT_SORT_ORDER);
        if (cursor != null) {
            if (cursor.moveToFirst()) {
                String smsAddress = cursor.getString(cursor.getColumnIndex("address"));
                String smsBody = cursor.getString(cursor.getColumnIndex("body"));
                String smsAdressTail = smsAddress.substring(smsAddress.length() - 5, smsAddress.length());
                if (!TextUtils.isEmpty(mSmsBodyContains) && !TextUtils.isEmpty(smsBody) && smsBody.contains(mSmsBodyContains)) {
                    smsContent = parseSmsBody(smsBody);
                    if (!TextUtils.isEmpty(smsContent)) {
                        mSmsListener.onResult(smsContent);
                    }
                } else if (mAddressTail.equals(smsAdressTail)) {
//                    "10473"
                    smsContent = parseSmsBody(smsBody);
                    if (!TextUtils.isEmpty(smsContent)) {
                        mSmsListener.onResult(smsContent);
                    }
                }
            }
        }
    }

    /**
     * 解析短信得到验证码
     *
     * @param smsBody
     * @return 验证码
     */
    private String parseSmsBody(String smsBody) {
        // 匹配规则为短信中的连续4位数字
        String regEx = new String("(\\d{6})");
        // 验证码
        String smsCode = "";

//                    String regEx = "[^0-9]";
        Pattern pattern = Pattern.compile(regEx);
        Matcher matcher = pattern.matcher(smsBody);
        // 如果匹配到了
        while (matcher.find()) {
            smsCode = matcher.group(0);
        }
        LogUtils.i("获取短信验证码     " + "smsCode = " + smsCode);
        return smsCode;
    }

    /**
     * 短信回调接口
     */
    public interface SmsListener {
        /**
         * 接受sms状态
         *
         * @Title: onResult
         */
        void onResult(String smsContent);
    }
}
